package org.shushan.cloud.transaction.sample.controller;


import org.apache.curator.framework.CuratorFramework;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.shushan.cloud.transaction.sample.entity.RoleEntity;
import org.shushan.cloud.transaction.sample.service.RoleService;
import org.shushan.cloud.transaction.sample.vo.RolePageRequest;
import org.shushan.cloud.transaction.sample.vo.RoleRequest;
import org.shushan.cloud.transaction.sample.vo.RoleResponse;
import org.shushan.framework.core.resp.Result;
import org.shushan.framework.web.base.CrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhigang.li
 * @date 2022/6/19
 
 
 */
@RestController
@RequestMapping("Role")
public class RoleController extends CrudController<RolePageRequest, RoleRequest, RoleResponse, String, RoleEntity, RoleService> {

    @GetMapping("test")
    @ResponseBody
    public String test(String name, String id) {
        return service.test(name, id);
    }


    @Autowired
    CuratorFramework client;

    @ResponseBody
    @PostMapping({"transaction"})
    public Result<RoleResponse> transaction(@Validated @RequestBody RoleRequest request) {
        this.service.saveTransaction(request);
        return Result.ok();
    }

    @GetMapping("lock")
    @ResponseBody
    public String lock() throws InterruptedException {

        for (int i = 0; i < 10; i++) {
            service.lock(i);
        }
        return "lock";
    }

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    //测试消息的发送,事务消息发送
    @GetMapping("rocketmq")
    public String rocketmq() {
        RoleEntity RoleEntity = new RoleEntity();
        RoleEntity.setId("dafdafd12121121da");
        Message<RoleEntity> message = MessageBuilder.withPayload(RoleEntity).build();
        //传入一个TransactionLocalService来执行本地业务逻辑
        rocketMQTemplate.sendMessageInTransaction("testmq", message, null);
        return "ok";
    }

}
